//Copyright (c) 2017. 章钦豪. All rights reserved.
package com.kunfei.bookshelf.view.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.kunfei.basemvplib.impl.IPresenter;
import com.kunfei.bookshelf.DbHelper;
import com.kunfei.bookshelf.R;
import com.kunfei.bookshelf.base.MBaseActivity;
import com.kunfei.bookshelf.base.observer.MyObserver;
import com.kunfei.bookshelf.bean.BookSourceBean;
import com.kunfei.bookshelf.model.BookSourceManager;
import com.kunfei.bookshelf.presenter.ReadBookPresenter;
import com.kunfei.bookshelf.utils.theme.ThemeStore;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

public class WelcomeActivity extends MBaseActivity
{

    @BindView(R.id.iv_bg)
    ImageView ivBg;

    @Override
    protected IPresenter initInjector()
    {
        return null;
    }

    @Override
    protected void onCreateActivity()
    {
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0)
        {
            finish();
            return;
        }
        setContentView(R.layout.activity_welcome);
        AsyncTask.execute(DbHelper::getDaoSession);
        ButterKnife.bind(this);
        ivBg.setColorFilter(ThemeStore.accentColor(this));
        ValueAnimator welAnimator = ValueAnimator.ofFloat(1f, 0f).setDuration(800);
        welAnimator.setStartDelay(500);
        welAnimator.addUpdateListener(animation -> {
            float alpha = (Float) animation.getAnimatedValue();
            ivBg.setAlpha(alpha);
        });
        welAnimator.addListener(new Animator.AnimatorListener()
        {
            @Override
            public void onAnimationStart(Animator animation)
            {
                if (preferences.getBoolean(getString(R.string.pk_default_read), false))
                {
                    startReadActivity();
                } else
                {
                    startBookshelfActivity();
                }
                finish();
            }

            @Override
            public void onAnimationEnd(Animator animation)
            {

            }

            @Override
            public void onAnimationCancel(Animator animation)
            {

            }

            @Override
            public void onAnimationRepeat(Animator animation)
            {

            }
        });
        welAnimator.start();
    }

    private void startBookshelfActivity()
    {
        startActivityByAnim(new Intent(this, MainActivity.class), android.R.anim.fade_in, android.R.anim.fade_out);
    }

    private void startReadActivity()
    {
        Intent intent = new Intent(this, ReadBookActivity.class);
        intent.putExtra("openFrom", ReadBookPresenter.OPEN_FROM_APP);
        startActivity(intent);
    }

    @Override
    protected void initData()
    {
        if (preferences.getBoolean("importDefaultBookSource", false))
            return;
        try
        {
            InputStream inputStream = getAssets().open("bookSource.json");
            InputStreamReader inputStreamReader = null;
            try
            {
                inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            } catch (UnsupportedEncodingException e1)
            {
                e1.printStackTrace();
            }
            BufferedReader reader = new BufferedReader(inputStreamReader);
            StringBuffer sb = new StringBuffer("");
            String line;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            Observable<List<BookSourceBean>> observable = BookSourceManager.importSource(sb.toString());
            if (observable != null)
            {
                observable.subscribe(new MyObserver<List<BookSourceBean>>()
                {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void onNext(List<BookSourceBean> bookSourceBeans)
                    {
                        if (bookSourceBeans.size() > 0)
                        {
                            preferences.edit()
                                    .putBoolean("importDefaultBookSource", true)
                                    .apply();
                        } else
                        {
                            preferences.edit()
                                    .putBoolean("importDefaultBookSource", false)
                                    .apply();
                        }
                    }

                    @Override
                    public void onError(Throwable e)
                    {
                        preferences.edit()
                                .putBoolean("importDefaultBookSource", false)
                                .apply();
                    }
                });
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
